


Imports System.Data.OleDb

Public Class Form2

    'mi conexion
    Public Conexion As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\Database.accdb")
    'por medio de esta variable voy a trasmitir los datos
    Public conm As New OleDb.OleDbCommand
    Dim sql As String
    Dim SQL2 As String

    Private cn As OleDbConnection = New OleDbConnection
    Private dv As New DataView
    Dim ds As New DataSet
    Dim Da As New OleDbDataAdapter("SELECT MAX(ID) FROM factura", Conexion)



    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            Conexion.Open()
            Me.Text = " Panel principal                                       ::::::  Conectado a la base de datos  ::::: "
            conm.Connection = Conexion
            conm.CommandType = CommandType.Text

        Catch ex As Exception
            If Err.Number = 5 Then
                MsgBox("No se pudo encotrar el archivo de la base de datos", vbCritical)
                End

            Else
                MsgBox(Err.Description)

            End If



        End Try
    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        PanelFacturar.Enabled = False
        PanelFacturar.Visible = False
    End Sub
    'boton Buscar
    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Form3.Show()
    End Sub
    'Boton Agregar
    Private Sub ButtonaAgregar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonaAgregar.Click


        'contador de items para el maximo que se pueden facturar

        Dim cont As Double = 0
        Dim contar As Double = 0
        Dim ilera As DataGridViewRow = New DataGridViewRow

        
        For Each ilera In DataGridView1.Rows
            cont += Convert.ToDouble(ilera.Cells("contador").Value)
            contar += Convert.ToDouble(ilera.Cells("importes").Value)

        Next

        TextBox3.Text = Convert.ToString(cont)
        TextBox1.Text = Convert.ToString(contar)





        'sentencia del contador

        If TextBox3.Text = "10" Then

            MsgBox("La factura se encuentra llena", vbExclamation)
            TextCodigo.Text = ""

        Else
            If Buscar(TextCodigo.Text) = True Then
                PictureBox6.Enabled = True
                PictureBox7.Enabled = True
            Else
                MsgBox("El codigo no exite", vbCritical)
            End If

            TextCodigo.Text = ""
            TextCodigo.Focus()

        End If

    End Sub


    'agregar con enter
    Private Sub TextCodigo_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextCodigo.KeyPress


        'contador


        Dim cont As Double = 0
        Dim ilera As DataGridViewRow = New DataGridViewRow

        For Each ilera In DataGridView1.Rows
            cont += Convert.ToDouble(ilera.Cells("contador").Value)


        Next

        TextBox3.Text = Convert.ToString(cont)


        If TextBox3.Text = "10" Then

            TextCodigo.Text = ""
            MsgBox("La factura se encuentra llena", vbExclamation)
            TextCodigo.Text = ""

        Else


            If e.KeyChar = ChrW(Keys.Enter) Then
                If Buscar(TextCodigo.Text) = True Then
                    PictureBox6.Enabled = True
                    PictureBox7.Enabled = True

                Else
                    MsgBox("El codigo no exite", vbCritical)
                End If

                TextCodigo.Text = ""
                TextCodigo.Focus()
            End If
        End If

    End Sub

    'buscar en la base de datos

    Function Buscar(ByVal xId As String) As Boolean

        'convertidor
        Dim Id As Double
        Id = Convert.ToInt32(xId)


        'conexion
        Dim Conexion As New OleDbConnection
        Conexion.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\Database.accdb"

        'puente
        Dim CadenaSQL As String = "SELECT * FROM productos WHERE id = " & Id

        'adaptador
        Dim Adaptador As New OleDbDataAdapter(CadenaSQL, Conexion)


        'date set

        Dim Ds As New DataSet

        'llenar data set

        Conexion.Open()
        Adaptador.Fill(Ds)
        Conexion.Close()


        'contar registro

        If (Ds.Tables(0).Rows.Count = 0) Then
            ' sin registro
            Return False

        Else
            'encontro registro

            DataGridView1.Rows.Add("1", Ds.Tables(0).Rows(0)("id").ToString(), Ds.Tables(0).Rows(0)("producto").ToString(), "1", TxtDescuento.Text, Ds.Tables(0).Rows(0)("Precio").ToString(), Ds.Tables(0).Rows(0)("Precio").ToString() - (Ds.Tables(0).Rows(0)("Precio").ToString() * (TxtDescuento.Text / 100)), TextBox2.Text)

            Ds.Dispose()

            Return True


        End If



    End Function

    'bloquear agregar si txtcodigo esta vacio
    Private Sub TextCodigo_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextCodigo.TextChanged

        If TextCodigo.Text = "" Then
            ButtonaAgregar.Enabled = False

        Else
            ButtonaAgregar.Enabled = True

        End If
    End Sub

    'suma de impuestos
    Private Sub TxtDescuento_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TxtDescuento.TextChanged

        If TxtDescuento.Text = "" Then
            TxtDescuento.Text = "0"
            TextObservaciones.Text = ""

        ElseIf TxtDescuento.Text = "0" Then
            TextObservaciones.Text = ""

        Else
            TextObservaciones.Text = "Se aplico un descuento de % " + TxtDescuento.Text

        End If


    End Sub


    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged

        Dim SubTotal, IVA, Total As Double

        SubTotal = TextBox1.Text
        Total = SubTotal * 1.22
        IVA = Total - SubTotal


        LabelSubTotal.Text = SubTotal
        LabelIVA.Text = IVA
        LabelTotal.Text = Total




    End Sub
    'Calculos modificando el datagrid
    Private Sub DataGridView1_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit



        Dim PrecioUnitario As Double = DataGridView1("Precio", e.RowIndex).Value
        Dim Descuento As Double = DataGridView1("Descuento", e.RowIndex).Value
        Dim Cantidad As Double = DataGridView1("Cantidad", e.RowIndex).Value
        Dim Apagar As Double = (PrecioUnitario * Cantidad)
        Dim ImporteApagar As Double = Apagar - (Apagar * (Descuento / 100))


        Try

            'Si modificamos columna Cantidad
            If (e.ColumnIndex = 0) Then

                DataGridView1("Importes", e.RowIndex).Value = ImporteApagar




            End If


            'Modificando Columna Descuento
            If (e.ColumnIndex = 4) Then

                DataGridView1("Importes", e.RowIndex).Value = ImporteApagar

            End If

            'modificando columna precio

            If (e.ColumnIndex = 5) Then

                DataGridView1("Importes", e.RowIndex).Value = ImporteApagar

            End If

        Catch ex As Exception

        End Try


    End Sub

    Private Sub PictureBox7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox7.Click



        ' Validar los campos

        If TexCliente.Text = "" Or TxtDireccion.Text = "" Or TxtRUT.Text = "" Or TxtTelefono.Text = "" Or TextObservaciones.Text = "" Then
            If TexCliente.Text = "" Then
                TexCliente.Text = "Consumidor Final"
            End If
            If TxtDireccion.Text = "" Then
                TxtDireccion.Text = "Sin Direccin"
            End If
            If TxtRUT.Text = "" Then
                TxtRUT.Text = "------------"
                If TxtTelefono.Text = "" Then
                    TxtTelefono.Text = "Sin Telfono"
                End If
            End If
            If TextObservaciones.Text = "" Then
                TextObservaciones.Text = "Sin Observaciones"
            End If

        End If

        sql = "INSERT INTO Factura (Cliente,Direccion,Rut,Telefono,Tipo_Documento,Moneda,Observacion,SubTotal,IVA,Total) VALUES ('" & _
                       TexCliente.Text & "', '" & TxtDireccion.Text & "', '" & TxtRUT.Text & "', '" & TxtTelefono.Text & "', '" & ComboDocumento.Text & "', '" & ComboMoneda.Text & "', '" & _
                        TextObservaciones.Text & "', " & LabelSubTotal.Text & ", " & LabelIVA.Text & ", " & LabelTotal.Text & ")"


        'SQL2 = "INSERTE INTO DetallesFactura (IDFactura, Cantidad, Codigo, Detalle, Descuento, Precio, Importe) VALUE  (" & _
        'DataGridView1.Item(8, ) & ", '" & DataGridView1.Rows.Add("Cantidad") & "', '" & DataGridView1.Rows.Add("codigo") & "', '" & _
        'DataGridView1.Rows.Add("detalle") & "', '" & DataGridView1.Rows.Add("Descuento") & "', '" & DataGridView1.Rows.Add("precio") & "', '" & _
        'DataGridView1.Rows.Add("importes") & "')"

        'SQL2 = "INSERT INTO Detallesfactura set IdFactura = '" &CStr(row.Cells("IdFacturas").Value & "', Cantidad = '" & CStr(row.Cells("Cantidad").Value & _
        ' "', Codigo = '" &CStr(row.Cells("codigo").Value & "', Detalle = '" & CStr(row.Cells("Detalle").Value & "', Descuento = '" & CStr(row.Cells("Descuento").value & _
        '         "', Precio = '" & CStr(row.Cells("Precio").Value & "', Importe = '" & CStr(row.Cells("importes").Value & "' "


        conm.CommandText = sql
        'conm.CommandText = SQL2


        Try
            conm.ExecuteNonQuery()
            limpiar()
            PictureBox6.Enabled = False
            PictureBox7.Enabled = False
            TextBox2.Text = TextBox2.Text + 1

        Catch ex As Exception
            MsgBox("Error al Guardar N " & Err.Number & " - " & Err.Description, MsgBoxStyle.Critical)
        End Try




    End Sub






    'Funciones de lo menus
    Private Sub NuevoClienteToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NuevoClienteToolStripMenuItem.Click
        Nuevo_Cliente.Show()
        PanelFacturar.Enabled = False
        PanelFacturar.Visible = False

    End Sub

    Private Sub BuscarFacturaEmitidaToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BuscarFacturaEmitidaToolStripMenuItem.Click
        Facturas_Emitidas.Show()
        PanelFacturar.Enabled = False
        PanelFacturar.Visible = False

    End Sub

    Private Sub NuevoProductoToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NuevoProductoToolStripMenuItem.Click
        Articulos.Show()
        PanelFacturar.Enabled = False
        PanelFacturar.Visible = False

    End Sub

    Private Sub GastosToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GastosToolStripMenuItem2.Click
        Gastosvb.Show()
        PanelFacturar.Enabled = False
        PanelFacturar.Visible = False

    End Sub

    Private Sub ComprasToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComprasToolStripMenuItem1.Click
        Compras.Show()
        PanelFacturar.Enabled = False
        PanelFacturar.Visible = False

    End Sub

    Private Sub CajaToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CajaToolStripMenuItem2.Click
        Caja.Show()

    End Sub

    Private Sub NuevaVentaToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NuevaVentaToolStripMenuItem.Click
        PanelFacturar.Enabled = True
        PanelFacturar.Visible = True


    End Sub

    Private Sub NuevoUsuarioToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NuevoUsuarioToolStripMenuItem1.Click
        Usuario.Show()
        PanelFacturar.Enabled = False
        PanelFacturar.Visible = False

    End Sub

    Private Sub ModificarUsuarioToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ModificarUsuarioToolStripMenuItem1.Click
        Usuario.Show()
        PanelFacturar.Enabled = False
        PanelFacturar.Visible = False

    End Sub

    Private Sub ModificarProductoToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ModificarProductoToolStripMenuItem.Click
        Articulos.Show()
        PanelFacturar.Enabled = False
        PanelFacturar.Visible = False

    End Sub
    'boton facturar
    Private Sub PictureBox3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox3.Click
        PanelFacturar.Enabled = True
        PanelFacturar.Visible = True

        ds.Clear()
        'cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\Database.accdb"

        Da.Fill(ds)
        dv.Table = ds.Tables(0)
        DataGridView2.DataSource = dv
        TextBox2.Text = (DataGridView2.Rows(0).Cells(0).Value + 1)


    End Sub

    Private Sub PictureBox5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox5.Click
        Caja.Show()
        PanelFacturar.Enabled = False
        PanelFacturar.Visible = False

    End Sub

    Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click
        End
    End Sub

    Private Sub PictureBox2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox2.Click
        Form4.Show()
    End Sub

    Private Sub limpiar()
        TexCliente.Text = ""
        TxtTelefono.Text = ""
        TxtDireccion.Text = ""
        TxtRUT.Text = ""
        TextObservaciones.Text = ""
        TxtDescuento.Text = "0"
        ComboDocumento.Text = "Contado"
        ComboMoneda.Text = "Pesos"
        DataGridView1.Rows.Clear()

    End Sub


    Private Sub PictureBox8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox8.Click
        limpiar()
    End Sub

 
    Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
        Label21.Text = TextBox2.Text
    End Sub

End Class